home *** CD-ROM | disk | FTP | other *** search
/ CD-ROM Today - The Disc! 5 / CD-ROM Today - The Disc (Issue 5)(November 1994).ISO / mac / Mac shareware / Education / RLaB / rlib / trace.r < prev    next >
Encoding:
Text File  |  1994-09-21  |  533 b   |  27 lines  |  [TEXT/ttxt]

  1. //-------------------------------------------------------------------//
  2.  
  3. //  Syntax:    trace ( A )
  4.  
  5. //  Description:
  6.  
  7. //  Compute the trace (the sum of the diagonal elements) for the input
  8. //  matrix. `trace(A)' is the same as `sum( diag( A ) )'.
  9.  
  10. //-------------------------------------------------------------------//
  11.  
  12. trace = function(m) 
  13. {
  14.   local(i, tr);
  15.  
  16.   if(m.class != "num") { 
  17.     error("must provide NUMERICAL input to trace()");
  18.   }
  19.  
  20.   tr = 0;
  21.   for(i in 1:min( [m.nr, m.nc] )) {
  22.     tr = tr + m[i;i];
  23.   }
  24.  
  25.   return tr;
  26. };
  27.